package socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.sql.ClientInfoStatus;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    // 服务端Socket，用于监听客户端连接
    private ServerSocket serverSocket;
    private ExecutorService threadPool;
    private List<PrintWriter> allOut;

    public Server() {
        try {
            System.out.println("正在连接服务端");
            serverSocket = new ServerSocket(8088);
            threadPool = Executors.newFixedThreadPool(30);
            System.out.println("连接成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
 * 启动服务端，等待客户端连接
 * 该方法尝试接受客户端的连接请求，并在连接成功时打印消息
 */
public void start(){
    try {
        int number = 0;
        // 打印等待客户端连接的消息
        while (true) {
            System.out.println("等待客户端连接。。。");

            // 使用serverSocket接受客户端连接请求
            // 这里可能会阻塞，直到有客户端连接
            Socket socket = serverSocket.accept();

            // 当客户端连接成功后，打印成功消息
            System.out.println("第"+(++number)+"客户端连接成功了！");
           ClientHandler handler = new ClientHandler(socket, number);
//           Thread t1 = new Thread(handler);
//           t1.start();
            threadPool.execute(handler);
        }
//        int len ;
//        InputStream in = socket.getInputStream();
//        while ((len = in.read()) != -1) {
//            byte[] data = new byte[len];
//            in.read(data);
//            String message = new String(data, StandardCharsets.UTF_8);
//            System.out.println("客户端说："+message);
//        }
    } catch (IOException e) {
        // 捕获IOException并打印堆栈跟踪信息
        // 这里不处理异常，只是打印异常信息
        e.printStackTrace();
    }
}
    public class ClientHandler implements Runnable{
    private Socket socket;
    int number = 0;
        public ClientHandler() {
        }

        public ClientHandler(Socket socket) {
            this.socket = socket;
        }

        public ClientHandler(Socket socket, int number) {
            this.socket = socket;
            this.number = number;
        }

        @Override
        public void run() {
            try {
                int len ;
                InputStream in = socket.getInputStream();
                while ((len = in.read()) != -1) {
                    byte[] data = new byte[len];
                    in.read(data);
                    String message = new String(data, StandardCharsets.UTF_8);
                    System.out.println("第"+number+"客户端说：" + message);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }


    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }


}
